package br.unirn.exemplos.servlet;

import java.io.IOException;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import br.unirn.exemplos.dao.PostDao;
import br.unirn.exemplos.dominio.Post;
import br.unirn.exemplos.dominio.Usuario;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/PostServlet")
public class PostServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public PostServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		String operacao = request.getParameter("operacao");

		HttpSession session = request.getSession();
		if (operacao != null && operacao.equals("postar")){
			PostDao dao = new PostDao();
			
			try{
				Usuario usuario = (Usuario) session.getAttribute("usuarioLogado");
				String post = request.getParameter("post");
				
				Post p = new Post();
				
				p.setDataCadastro(new Date());
				
				p.setUsuario(usuario);
				
				p.setDescricao(post);
				
				dao.save(p);

				@SuppressWarnings("unchecked")
				List<Post> posts = (List<Post>) session.getAttribute("tweets");
				
				if (usuario != null){
					
					posts = dao.findPosts(usuario);

					session.setAttribute("tweets", posts);
				}
				
			}finally{
				if (dao!= null)
					dao.close();
			}
		}

		response.sendRedirect(request.getContextPath() + "/sistema/timeline.jsp");
		
		return;

	}

}
